package com.ruitaowang.admin.view.api;

import java.util.ArrayList;
import java.util.List;

import com.ruitaowang.goods.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ruitaowang.admin.tree.TreeNode;
import com.ruitaowang.core.domain.Category;
import com.ruitaowang.core.domain.GoodsCategory;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.service.GoodsCategoryService;

/**
 * Created by neal on 11/17/16.
 */
@RestController
public class APIGoodsCategoryController extends BaseController {

    @Autowired
    private GoodsCategoryService goodsCategoryService;
    @Autowired
    private CategoryService categoryService;

    @RequestMapping("/api/categories")
    public String list() {
        List<GoodsCategory> list;
        GoodsCategory goodsCategory = new GoodsCategory();
        goodsCategory.setOrderBy("category_sort asc");
        list = goodsCategoryService.select(goodsCategory);
        MsgOut o = MsgOut.success(list);
        return this.renderJson(o);
    }
    /**
     * @api {get} /api/admin/categories 后台管理-商品管理-获取商品分类
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/categories
     *
     * @apiName findGoodsCategory
     * @apiGroup Categories
     *
     * @apiParam {int} page 第几页.
     * @apiParam {int} rows 每页条数.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *               "categoryAmount": 0,
     *               "categoryDesc": "",
     *               "categoryHidden": 1,
     *               "categoryId": 9,
     *               "categoryName": "美妆洗护",
     *               "categorySmallIcon": "",
     *               "categorySort": 0,
     *               "categoryUnit": "",
     *               "ctime": 1484202750015,
     *               "mtime": 1484647065567,
     *               "navShow": 1,
     *               "parentCategoryId": 0,
     *               "rstatus": 0
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/categories"
     *  }
     */
    @RequestMapping("/api/admin/categories/get")
    public String findGoodsCategory() {
        List<Category> list;
        list = categoryService.select(new Category());
        MsgOut o = MsgOut.success(list);
        return this.renderJson(o);
    }
    @RequestMapping("/admin/categories/get")
    public String GoodsCategorySelectAll(GoodsCategory goodsCategory) {
        List<GoodsCategory> list;
        goodsCategory.setOrderBy("category_sort asc");
        list = goodsCategoryService.select(goodsCategory);
        MsgOut o = MsgOut.success(list);
        return this.renderJson(o);
    }
    @RequestMapping("/admin/categories/getList")
    public String GoodsCategoryForPage(GoodsCategory goodsCategory,int page) {
        List<GoodsCategory> list;
        goodsCategory.setPage(page);
        goodsCategory.setOrderBy("category_sort asc");
        list = goodsCategoryService.select(goodsCategory);
        MsgOut o = MsgOut.success(list);
        return this.renderJson(o);
    }
    @RequestMapping("/api/wap/categories/get")
    public String wapFindGoodsCategory() {
        List<GoodsCategory> list;
        GoodsCategory goodsCategory = new GoodsCategory();
        goodsCategory.setOrderBy("category_sort asc");
        list = goodsCategoryService.select(goodsCategory);
        MsgOut o = MsgOut.success(list);
        return this.renderJson(o);
    }
    /**
     * @api {post} /api/categoriess 后台管理-商品管理-创建商品分类
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/categories
     * @apiPermission admin
     *
     * @apiName createGoodsCategory
     * @apiGroup Categories
     *
     * @apiParam {long} parentCategoryId 商品上级分类ID.
     * @apiParam {int} categorySort 分类排序.
     * @apiParam {Byte} categoryHidden 1， 隐藏不显,0， 前端显示.
     * @apiParam {int} navShow 显示在导航栏1 是0 否,.
     * @apiParam {int} categoryRecommend 推荐.
     * @apiParam {string} categorySmallIcon 图标.
     * @apiParam {string} categoryDesc 排序.
     * @apiParam {string} categoryName 商品分类名称.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":
     *           {
     *               "categoryDesc": "1",
     *               "categoryHidden": 1,
     *               "categoryId": 24,
     *               "categoryName": "111111",
     *               "categorySmallIcon": "1",
     *               "categorySort": 1,
     *               "ctime": 1504679067403,
     *               "mtime": 1504679067403,
     *               "navShow": 1,
     *               "parentCategoryId": 0
     *           },
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/categories"
     *  }
     */
    @RequestMapping(value = "/api/admin/categories/post", method = RequestMethod.POST)
    public String createGoodsCategory(GoodsCategory goodsCategory) {
        goodsCategoryService.insert(goodsCategory);
        MsgOut o = MsgOut.success(goodsCategory);
        return this.renderJson(o);
    }
    @RequestMapping(value = "/admin/categories/post", method = RequestMethod.POST)
    public String adminCreateGoodsCategory(GoodsCategory goodsCategory) {
        goodsCategoryService.insert(goodsCategory);
        MsgOut o = MsgOut.success(goodsCategory);
        return this.renderJson(o);
    }
    /**
     * @api {put} /api/categories 更新活动
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/categories
     * @apiPermission admin
     *
     * @apiName updateGoodsCategory
     * @apiGroup GoodsCategory
     *
     * @apiParam {long} parentCategoryId 商品上级分类ID.
     * @apiParam {int} categorySort 分类排序.
     * @apiParam {Byte} categoryHidden 1， 隐藏不显,0， 前端显示.
     * @apiParam {int} navShow 显示在导航栏1 是0 否,.
     * @apiParam {int} categoryRecommend 推荐.
     * @apiParam {string} categorySmallIcon 图标.
     * @apiParam {string} categoryDesc 排序.
     * @apiParam {string} categoryName 商品分类名称.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":
     *           {
     *               "categoryDesc": "1",
     *               "categoryHidden": 1,
     *               "categoryId": 24,
     *               "categoryName": "111111",
     *               "categorySmallIcon": "1",
     *               "categorySort": 1,
     *               "ctime": 1504679067403,
     *               "mtime": 1504679067403,
     *               "navShow": 1,
     *               "parentCategoryId": 0

     *           },
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/categories"
     *  }
     */
    @RequestMapping(value = "/api/admin/categories/put", method = RequestMethod.PUT)
    public String updateGoodsCategory(Category category) {
        categoryService.update(category);
        MsgOut o = MsgOut.success(category);
        return this.renderJson(o);
    }
    @RequestMapping(value = "/admin/categories/put", method = RequestMethod.PUT)
    public String adminUpdateGoodsCategory(GoodsCategory category) {
        goodsCategoryService.update(category);
        MsgOut o = MsgOut.success(category);
        return this.renderJson(o);
    }
    /**
     * @api {get} /api/categories 后台管理-商品管理-获取商品分类ByPK
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/categories
     *
     * @apiName findGoodsCategoryByPK
     * @apiGroup Categories
     *
     * @apiParam {long} categoryId 分类ID.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *               "categoryAmount": 0,
     *               "categoryDesc": "",
     *               "categoryHidden": 1,
     *               "categoryId": 9,
     *               "categoryName": "美妆洗护",
     *               "categorySmallIcon": "",
     *               "categorySort": 0,
     *               "categoryUnit": "",
     *               "ctime": 1484202750015,
     *               "mtime": 1484647065567,
     *               "navShow": 1,
     *               "parentCategoryId": 0,
     *               "rstatus": 0
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/categories"
     *  }
     */
    @RequestMapping(value = "/api/categories/get/{categoryId}", method = RequestMethod.GET)
    public String findGoodsCategoryByPK(@PathVariable("categoryId") Long categoryId) {
        MsgOut o = MsgOut.success(goodsCategoryService.selectByPK(categoryId));
        return this.renderJson(o);
    }
    /**
     * @api {delete} /api/admin/categories/delete/:categoryId 后台管理-商品管理-商品分类-删除
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/admin/categories/delete/:categoryId
     * @apiPermission admin
     *
     * @apiName deleteGoodsCategory
     * @apiGroup GoodsCategory
     *
     * @apiParam {long} categoryId 活动编号.
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":1,
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/admin/categories/{categoryId}"
     *  }
     */
    @RequestMapping(value = "/api/admin/categories/delete/{categoryId}", method = RequestMethod.DELETE)
    public String deleteGoodsCategory(@PathVariable("categoryId") Long categoryId) {
        MsgOut o = MsgOut.success(categoryService.delete(categoryId));
        return this.renderJson(o);
    }
    @RequestMapping(value = "/admin/categories/delete/{categoryId}", method = RequestMethod.DELETE)
    public String adminDeleteGoodsCategory(@PathVariable("categoryId") Long categoryId) {
        MsgOut o = MsgOut.success(goodsCategoryService.delete(categoryId));
        return this.renderJson(o);
    }
    @RequestMapping(value = "/api/cateTree", method = RequestMethod.GET)
	public String cateTree() {

		// cate.setParentId(0L);
		List<TreeNode> nodes = new ArrayList<>();
        /*TreeNode root = new TreeNode();
		root.setId(0L);
		root.setpId(-1L);
		root.setName("根");
		nodes.add(root);*/
		List<Category> cates = categoryService.select(new Category());
		
		List<Category> level1 = getChildren(cates, 0L);
		
		for (Category c1 : level1) {
			nodes.add(cloneCate(c1, new TreeNode()));
			List<Category> level2 = getChildren(cates, c1.getId());
			for (Category c2 : level2) {
				nodes.add(cloneCate(c2, new TreeNode()));
				List<Category> level3 = getChildren(cates, c2.getId());
				for (Category c3 : level3) {
					nodes.add(cloneCate(c3, new TreeNode()));
				}
			}
		}

		return this.renderJson(nodes);
	}
    
	private TreeNode cloneCate(Category c,TreeNode n){
		n.setId(c.getId());
		n.setName(c.getName());
		n.setpId(c.getParentId());
		
		return n;
	}
    
	private List<Category> getChildren(List<Category> cates, Long pid) {

		List<Category> children = new ArrayList<>();
		for (Category c : cates) {
			if(c.getParentId().equals(pid)){
				children.add(c);
			}
		}
		
		cates.removeAll(children);

		return children;
	}
}
